<template>
  <div>
    <div class="search">
      <input type="text"
             v-model="keyword"
             class="search-box"
             placeholder="请输入城市">
    </div>
    <div class="search-content"
         ref="wrapper"
         v-show="keyword.length">
      <ul>
        <li class="item border-bottom"
            v-for="item of list"
            :key="item.id"
            @click="handleChangeCity(item.name)">{{item.name}}</li>
        <li class="item"
            v-show="!list.length">抱歉，没有搜索结果</li>
      </ul>
    </div>
  </div>
</template>
<script>
import BScroll from 'better-scroll'
import { mapMutations } from 'vuex'
export default {
  name: 'CitySearch',
  props: {
    cities: Object
  },
  data () {
    return {
      keyword: ''
    }
  },
  methods: {
    handleChangeCity (city) {
      // 派发一个mutations
      this.changeCity(city)
      this.$router.push('/')
    },
    ...mapMutations(['changeCity'])
  },
  mounted () {
    this.scroll = new BScroll(this.$refs.wrapper, {
      click: true
    })
  },
  computed: {
    list () {
      let result = []
      for (let key in this.cities) {
        this.cities[key].forEach(item => {
          if (item.spell.indexOf(this.keyword) > -1 || item.name.indexOf(this.keyword) > -1) {
            result.push(item)
          }
        })
      }
      return result
    }
  }
}
</script>
<style lang="stylus" scoped>
@import '~styles/varibles.styl'
.search
  height: 0.72rem
  padding: 0.1rem
  background: $bgColor
  .search-box
    width: 100%
    height: 0.62rem
    line-height: 0.62rem
    padding: 0 0.1rem
    box-sizing: border-box
    text-align: center
    border-radius: 0.1rem
    color: #666
.search-content
  position: absolute
  top: 1.6rem
  bottom: 0
  left: 0
  right: 0
  overflow: hidden
  background: #eee
  z-index: 1
  .item
    line-height: 0.7rem
    padding-left: 0.2rem
</style>
